import React, { Component } from "react";
import { connect } from "react-redux";
import MainLayout from "../../../../component/mainLayout/mainLayout";
import "./RechargeAccount.scss";
import { InputItem, List, Modal, Toast } from "antd-mobile";
const alerts = Modal.alert;
import yhTools from "../../../../tools/yh";
import { channelCode, InterfaceG } from "../../../../config/Config";
import copy from "copy-to-clipboard";
import { checkTool } from "plugin-tool-check";
// import eyeOffLine from '@images/imageXHB/eye-off-line.png';

const Item = List.Item;

class RechargeAccount extends Component {
	constructor(props) {
		super(props);
		/**
		 * 如果是原生进入充值界面,index_fromType = app
		 * 返回键直接关闭page
		 */
		let index_fromType = sessionStorage.getItem("index_fromType");
		let flag = index_fromType && index_fromType === "app";
		this.state = {
			showAmt: false, //是否显示真实金额
			loadStatus: "1", // （ '0'：数据加载中，'1'：加载完成，'2'：加载失败）
			msgSubmitButtStatus: "3", // 底部按钮状态 '3':常态  '0':加载中 '1':加载成功 '2':'失败'
			showDialog: "moreAccountDialog", //显示大额提示框
			msgSubmitButtText: "确认充值",
			errorTip: "", //金额错误提示
			showError: "1",
			inputValue: "",
			initData: {
				amount: "",
				cardAmount: "",
				cardDayAmount: "",
				cardName: "",
				cardNo: "",
				cardUrl: "",
				channelCode: "",
				channelName: "",
				electronicCardNo: "",
				telNo: ""
			},
			from: "", // 如果是从购买充值进入，则是返回到
			modal1: false,
			/** 是否回退到app */
			flag
		};
		/** 界面类型 0是正常途径进入，1是还款进入*/
		this._pagetype = props.location.pathname.indexOf("xhb") === -1 ? 0 : 1;
	}

	//初始化数据
	componentDidMount() {
		const from = yhTools.getUrlParam("from");
		this.setState({
			from
		});
		//初始化数据
		let objs = {
			url: InterfaceG.electronicAmount,
			params: {
				channelCode: channelCode,
				type: "0" // 充值
			},
			_alertShow: false
		};
		yhTools.request(objs).then(resp => {
			if (resp.code == "0") {
				this.setState({
					initData: {
						amount: resp.data.amount,
						cardAmount: resp.data.cardAmount,
						cardDayAmount: resp.data.cardDayAmount,
						cardName: resp.data.cardName,
						cardNo: resp.data.cardNo.slice(resp.data.cardNo.length - 4),
						cardUrl: resp.data.cardUrl,
						channelCode: resp.data.channelCode,
						channelName: resp.data.channelName,
						electronicCardNoOrigin: resp.data.electronicCardNo,
						electronicCardNo: resp.data.electronicCardNo.slice(
							resp.data.electronicCardNo.length - 4
						),
						telNo: resp.data.telNo
					}
				});
			} else {
				Toast.info(resp.message, 2);
			}
		});
	}

	checkValue(value) {
		if (value == "") {
			this.setState({
				errorTip: "",
				inputValue: value
			});
			return;
		}
		let preValue = this.state.inputValue;
		if (value && !/^(([1-9]\d*)|0)(\.\d{0,2}?)?$/.test(value)) {
			if (value === ".") {
				value = "0.";
			} else {
				value = preValue;
			}
		}
		if (!checkTool.isMoney({ valueParams: value })) {
			if (this.state.errorTip != "请输入正确的金额") {
				this.setState({
					errorTip: "请输入正确的金额",
					inputValue: value
				});
			}
		} else if (Number(value) > Number(this.state.initData.cardAmount)) {
			if (
				this.state.errorTip !=
				"单笔上限" + this.state.initData.cardAmount + "元"
			) {
				this.setState({
					errorTip: (
						<div>
							<span style={{ color: "#ff3534" }}>充值金额超出单笔限额，</span>
							<span
								style={{ color: "#40B15D" }}
								onClick={this.openIntroduce.bind(this)}
							>
								戳这里，试试转账充值吧&gt;
							</span>
						</div>
					),
					inputValue: value
				});
			}
		} else {
			let checkValue = value.split(".");
			if (checkValue[0] < 100) {
				if (this.state.errorTip != "提现金额100元起") {
					this.setState({
						errorTip: "充值金额100元起",
						inputValue: value
					});
				}
			} else {
				this.setState({
					errorTip: "",
					inputValue: value
				});
			}
		}
	}
	/**
	 * 点击充值，先检查是否
	 */
	checkPass = () => {
		const value = this.state.inputValue;
		if (value == "") {
			Toast.info("请输入充值金额");
			return;
		}
		if (!checkTool.isMoney({ valueParams: value })) {
			if (this.state.errorTip == "请输入正确的金额") {
				Toast.info("请输入正确的金额");
				return;
			}
		} else if (Number(value) > Number(this.state.initData.cardAmount)) {
			Toast.info("充值金额超出单笔限额", 2);
			return;
		} else {
			let checkValue = value.split(".");
			if (checkValue[0] < 100) {
				if (this.state.errorTip == "充值金额100元起") {
					Toast.info("充值金额100元起", 2);
					return;
				}
			}
		}

		Toast.loading("加载中...", 100);
		yhTools
			.request({
				url: InterfaceG.xhbgetPassword,
				_alertShow: false,
				params: {}
			})
			.then(res => {
				Toast.hide();
				if (res.code === "0") {
					if (res.data.status == "0") {
						this.props.history.push({
							pathname: "/xhdsetPayPwd",
							state: {
								comePath: "rechargeAccount"
							}
						});
					} else {
						this.reChargeAction();
					}
				}
			});
	};
	/**
	 * 点击充值
	 */
	reChargeAction() {
		let objs = {
			url: InterfaceG.eleAcctSignQuery,
			params: {
				channelCode: channelCode,
				amount: this.state.inputValue
			},
			_alertShow: false
		};
		Toast.loading("正在提交中...", 100, () => { });
		yhTools.request(objs).then(resp => {
			Toast.hide();
			if (resp.code == "0") {
				//成功页面
				if (resp.data.pageIndex == "1") {
					// 不需要签约，跳转到充值发短信页面
					let data = {
						channelCode: channelCode,
						amount: this.state.inputValue,
						goBackIndex: -2
					};
					this.props.history.push({
						pathname: `/AuthenticatePayCode/${JSON.stringify(data)}`
					});
				} else if (resp.data.pageIndex == "0") {
					// 需要签约，跳转到签约页面
					let data = {
						channelCode: channelCode,
						amount: resp.data.amount,
						bankMobile: resp.data.bankMobile,
						cardNo: resp.data.cardNo,
						userName: resp.data.userName,
						bankName: resp.data.bankName,
						idCard: resp.data.idCard,
						payRouteCode: resp.data.payRouteCode
						// tradeNumber: resp.data.tradeNumber,
					};
					this.props.history.push({
						pathname: `/authPay/${JSON.stringify(data)}`
					});
				}
			} else {
				//失败页面
				Toast.info(resp.message, 2);
			}
		});
	}

	copyElECCardNo() {
		copy(this.state.initData.electronicCardNoOrigin);
		Toast.info("复制成功", 2);
	}
	/** 打电话 */
	callPhone(telphone) {
		let callPhoneData = {
			telphone
		};
		yhTools.callPhone(callPhoneData);
	}
	//打开大额介绍
	openIntroduce() {
		this.setState({ modal1: true });
	}
	handleShowAmt = () => {
		this.setState({
			showAmt: !this.state.showAmt
		});
	};
	render() {
		let commonParams = {
			title: "充值",
			headerBackground: '#BC9A67',
			goToApp: this.state.flag
		};
		const transferHeader = {
			...commonParams
		};
		const header = {
			...commonParams
			// goBackPath: "/bankDetailPage"
		};
		const headerParams = {
			header: this.state.from === "bankDetail" ? header : transferHeader,
			history: this.props.history,
			cacheLifecycles: this.props.cacheLifecycles,
			loadStatus: this.state.loadStatus // （ '0'：数据加载中，'1'：加载完成，'2'：加载失败）
		};
		return (
			<MainLayout pageParams={headerParams}>
				<div className="recharge-page">
					<div className="account-content">
						<div className="account-area">
							<div className="bank-top">
								<div className="bank-top-right">
									<div className="bank-top-right-top">
										账户余额(元):{" "}
										{this.state.showAmt ? this.state.initData.amount : "*****"}
										{this.state.showAmt ? (
											<img
												className="eye-line"
												src={require("../../../../images/imageXHB/eye-line.png")}
												alt=""
												onClick={this.handleShowAmt}
											/>
										) : (
											<img
												className="eye-off-line"
												src={require("../../../../images/imageXHB/eye-off-line.png")}
												alt=""
												onClick={this.handleShowAmt}
											/>
										)}
									</div>
									<div
										className="bank-top-right-bottom"
										onClick={this.copyElECCardNo.bind(this)}
									>
										复制卡号
									</div>
								</div>
							</div>
							<p className="bank-no">
								.... .... ....{" "}
								{this.state.initData.electronicCardNo.slice(
									this.state.initData.electronicCardNo.length - 4
								)}
							</p>
						</div>
					</div>
					<div className="new-bank-area">
						<p className="title">充值金额</p>
						<div className="box">
							<InputItem
								placeholder="充值金额100元起"
								type="money"
								moneyKeyboardAlign="left"
								maxLength="9"
								value={this.state.inputValue}
								onChange={this.checkValue.bind(this)}
							>
								¥
							</InputItem>
							<div className="error-tip error-tip-show">
								{this.state.errorTip}
							</div>
						</div>
						<div className="fenge"></div>
						<p className="titlek">付款银行卡</p>
						<List>
							<Item thumb={this.state.initData.cardUrl}>
								<div>
									<div className="bank-name">
										{this.state.initData.cardName +
											"(" +
											this.state.initData.cardNo +
											")"}
									</div>
									<div className="bankTip">
										{"单笔上限" +
											this.state.initData.cardAmount +
											"元,单日上限" +
											this.state.initData.cardDayAmount}
										元
									</div>
								</div>
							</Item>
						</List>
						<div className="fenge"></div>
					</div>
					<div className="btn-common" onClick={this.checkPass.bind(this)}>
						充值
					</div>
					<div className="area-tip">
						银行卡额度太低？
						<a onClick={this.openIntroduce.bind(this)}>试试转账充值吧&gt;</a>
					</div>
				</div>
				<Modal
					popup
					className="recharge-account-modal"
					visible={this.state.modal1}
					onClose={() => { }}
					animationType="slide-up"
				>
					<div className="div-far">
						<div className="line-1">
							<div className="title">转账充值</div>
							<img
								className="close-img"
								src={require("../../../../images/icon-open-account-close.png")}
								onClick={this.onCloseM()}
							/>
						</div>
						<div className="bind-card-name">
							请使用绑定卡
							<span>
								{this.state.initData.cardName}（尾号
								{this.state.initData.cardNo.slice(
									this.state.initData.cardNo.length - 4
								)}
								）
							</span>
							，向您的福建华通银行电子账户转账。
						</div>
						<div className="line-3">
							仅支持开户绑定银行卡，若非绑定卡转账，资金将于1日内退回。
						</div>
						<div className="line-4">
							<div className="item">
								<span className="title">收款账号</span>
								<span className="mg-l">
									{this.state.initData.electronicCardNoOrigin}
								</span>
								<span className="blue" onClick={this.copyElECCardNo.bind(this)}>
									复制
								</span>
							</div>
							<div className="fenge"></div>
							<div className="item">
								<span className="title">收款人</span>
								<span className="mg-l">您本人姓名</span>
							</div>
							<div className="item">
								<span className="title">开户行</span>
								<span className="mg-l">福建华通银行</span>
							</div>
							<div className="item">
								<span className="title"></span>
								<span className="mg-l t-c-y">
									若无可选择“民营银行/直销/其他”
								</span>
							</div>
							<div className="item">
								<span className="title">开户地</span>
								<span className="mg-l">福建福州</span>
							</div>
						</div>
						<div style={{ marginTop: "0.2rem" }}></div>
						<div className="line-6">
							<p>
								1、打开 <span>{this.state.initData.cardName}APP</span> 网上银行
							</p>
							<p className="p-c">
								2、进入转账页面，在收款账户信息处填写上方所示的华通
								银行电子账户信息
							</p>
							<p>3、输入金额，完成转账</p>
						</div>
						<div className="line-5">
							转账时间说明：
							<br />
							工作日8:30-17:00，预计2小时内到账；其他时段，次一工作日到账。{" "}
							<br />
							如有疑问，可联系
							<span
								onClick={() => {
									alerts("", "400 821 9666", [
										{ text: "取消", onPress: () => { } },
										{
											text: "呼叫",
											onPress: () => {
												this.callPhone(4008219666);
											}
										}
									]);
									let mask = document.getElementsByClassName("am-modal-mask");
									let wrap = document.getElementsByClassName("am-modal-wrap");
									mask[0].style.zIndex = 555;
									wrap[0].style.zIndex = 666;
									mask[1].style.zIndex = 777;
									wrap[1].style.zIndex = 888;
									wrap[1].style.background = "rgba(0, 0, 0, 0.4)";
								}}
							>
								华通银行客服
							</span>
							。
						</div>
					</div>
				</Modal>
			</MainLayout>
		);
	}
	onCloseM = () => () => {
		this.setState({
			modal1: false
		});
	};
}

function mapStateToProps(state) {
	return state;
}

function mapDispatchToProps() {
	return {};
}

const RechargeAccountPage = connect(
	mapStateToProps,
	mapDispatchToProps
)(RechargeAccount);
export default RechargeAccountPage;
